package com.mornd.gulimall.product.service.impl;

import cn.hutool.core.util.StrUtil;
import com.mornd.gulimall.common.core.utils.SeparatorUtil;
import com.mornd.gulimall.product.entity.Attr;
import com.mornd.gulimall.product.entity.ProductAttrValue;
import com.mornd.gulimall.product.entity.vo.spusave.SpecVo;
import com.mornd.gulimall.product.mapper.ProductAttrValueMapper;
import com.mornd.gulimall.product.service.IAttrService;
import com.mornd.gulimall.product.service.IProductAttrValueService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 * spu属性值 服务实现类
 * </p>
 *
 * @author mornd
 * @since 2023-07-23
 */
@Service
public class ProductAttrValueServiceImpl extends ServiceImpl<ProductAttrValueMapper, ProductAttrValue> implements IProductAttrValueService {
    @Resource
    private IAttrService attrService;

    @Override
    public void saveSpecs(Long spuId, List<SpecVo> specs) {
        List<ProductAttrValue> saves = new ArrayList<>();
        int sort = 0;
        for (SpecVo spec : specs) {
            // 过滤空字符串
            String filter = SeparatorUtil.filterBlank(spec.getValue());

            if (StrUtil.isBlank(filter)) {
                continue;
            }

            ProductAttrValue attrValue = new ProductAttrValue();

            attrValue.setSpuId(spuId);
            attrValue.setAttrId(spec.getAttrId());
            attrValue.setQuickShow(spec.getShowDesc());
            attrValue.setAttrValue(filter);
            attrValue.setAttrSort(sort++);

            Attr attr = attrService.getById(spec.getAttrId());
            if (attr != null) {
                attrValue.setAttrName(attr.getAttrName());
            }

            saves.add(attrValue);
        }

        super.saveBatch(saves);
    }
}
